<?php
/**
 * GioCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@ninhgio.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2010-2011 GioCMS (http://cms.ninhgio.com)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @author		NinhGio - ninhgio@gmail.com
 * @since		1.0
 */

class Modules_Category_Services_Category extends Modules_Category_Models_Category
{	
	const EOL = "\n";
	
	public static function factory()
	{
		$request = Gio_Core_Request::getInstance();
		$config = Gio_Core_Module::getConfig('category');
		$param = isset($config['url']['param']) ? $config['url']['param'] : 'category_id';
		$category = null;
		
		switch ($param) {
			case 'category_path':
				$category = Modules_Category_Services_Category::getByPath($request->getParam($param));
				break;
		}
		if (null == $category) {
			$category = Modules_Category_Services_Category::getById($request->getParam('category_id'));
		}
		
		return $category;
	}
	
	public static function validate($data)
	{
		$validator = new Gio_Core_Validator();
		foreach ($data as $index => $value) {
			if (gettype($value) == 'string') {
				$data[$index] = trim($value);
			}
		} 
		$data['messages']['name'] = $validator->setString($data['name'])
												->validate(array('notNull')
																, array(
																	'notNull' => 'category_name_notnull'
																)
														);
		$data['messages']['slug'] = $validator->setString($data['slug'])
												->validate(array('notNull')
																, array(
																	'notNull' => 'category_slug_notnull'
																)
														);
		$data['messages']['module_id'] = $validator->setString($data['module_id'])
												->validate(array('notNull')
																, array(
																	'notNull' => 'category_module_notnull'
																)
														);
		$data['messages']['language'] = $validator->setString($data['language'])
												->validate(array('notNull')
																, array(
																	'notNull' => 'category_language_notnull'
																)
														);
														
		$error = false;
		foreach ($data['messages'] as $index => $message) {
			if ($message) {
				$data['messages_error'] = true;
				return $data;
			}
		}										
		$data['messages_error'] = false;
		return $data;
	}
	
	public static function add($category, $sourceItem = null)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_Category_Models_Mysql_Category();
		$dao->setConnection($conn);
		$id = $dao->add($category);
		
		/**
		 * Translation
		 */
		$json 		 = new Services_JSON();
		$source 	 = (array)$json->decode($sourceItem);
		$translation = array(
							'item_id' 	      => $id,
							'item_class'      => get_parent_class($dao),
							'source_item_id'  => ('' == $source['id']) ? $id : $source['id'],
							'language'        => $category['language'],
							'source_language' => ('' == $source['language']) ? null : $source['language'],
					);
		Modules_Core_Services_Translation::add($translation);
		return $id;
	}
	
	public static function activate($category)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_Category_Models_Mysql_Category();
		$dao->setConnection($conn);
		$dao->update($category);
	}
	
	public static function delete($category)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_Category_Models_Mysql_Category();
		$dao->setConnection($conn);
		$dao->delete($category);
		
		Modules_Core_Services_Translation::delete($category['category_id'], get_parent_class($dao));
	}
		
	public static function update($category, $sourceItem = null)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_Category_Models_Mysql_Category();
		$dao->setConnection($conn);
		$dao->update($category);
		
		/**
		 * Translation
		 */
		$json 		 = new Services_JSON();
		$source 	 = (array)$json->decode($sourceItem);
		$translation = array(
							'item_id' 	      => $category['category_id'],
							'item_class'      => get_parent_class($dao),
							'source_item_id'  => (!isset($source['id']) || '' == $source['id']) ? $category['category_id'] : $source['id'],
							'language'        => $category['language'],
							'source_language' => ('' == $source['language']) ? null : $source['language'],
					);
		Modules_Core_Services_Translation::update($translation);
	}
	
	public static function getById($catgoryId)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_Category_Models_Mysql_Category();
		$dao->setConnection($conn);
		return $dao->getById($catgoryId);
	}
	
	public static function getByPath($catgoryPath)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_Category_Models_Mysql_Category();
		$dao->setConnection($conn);
		return $dao->getByPath($catgoryPath);
	}
	
	public static function getParents($catgoryId)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_Category_Models_Mysql_Category();
		$dao->setConnection($conn);
		return $dao->getParents($catgoryId);
	}
	
	public static function updateParents($lang, $module)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_Category_Models_Mysql_Category();
		$dao->setConnection($conn);
		return $dao->updateParents($catgoryId);
	}
	
	public static function find($condition = array(), $offset = null, $limit = null)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_Category_Models_Mysql_Category();
		$dao->setConnection($conn);
		return $dao->find($condition, $offset, $limit);
	}
	
	public static function count($condition = array())
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_Category_Models_Mysql_Category();
		$dao->setConnection($conn);
		return $dao->count($condition);
	}
	
	public static function categorySelect($attributes = array(), $lang = 'vi_VN', $module = 'news')
	{
		if (null == $lang) {
		}
		$json = new Services_JSON();
		
		$categories = self::getTree($lang, $module);
		$selectedId = isset($attributes['selected']) ? $attributes['selected'] : null;
		$disableId  = isset($attributes['disabled']) ? $attributes['disabled'] : null;
		
		$id = isset($attributes['id']) ? $attributes['id'] : null;
		$name = isset($attributes['name']) ? $attributes['name'] : null;
		
		$output 	= sprintf("<select name='%s' id='%s' viewHelperClass='%s' viewHelperAttributes='%s'>", 
							$attributes['name'],
							$attributes['id'],
							'Modules_Category_Services_Category::categorySelect',
							$json->encodeUnsafe($attributes)) . self::EOL
					. '<option value="0">---</option>' . self::EOL;
		
		foreach ($categories as $category) {
			$selected = ($selectedId == null || $selectedId != $category['category_id']) ? '' : ' selected="selected"';
			$disable  = ($disableId == null || $disableId != $category['category_id']) ? '' : ' disabled';
			$output  .= sprintf('<option value="%s"%s%s>%s</option>',
								$category['category_id'],
								$selected,
								$disable,
								str_repeat('---', $category['depth']) . $category['name']) . self::EOL;
		}
		$output .= '</select>' . self::EOL;

		return $output;
	}
	
	public static function categoryCheckbox($attributes = array(), $lang = null, $module = 'news')
	{
		if (null == $lang) {
		}
		
		$json = new Services_JSON();
		$categories = self::getTree($lang, $module);
		$output     = sprintf("<div id='%s' viewHelperClass='%s' viewHelperAttributes='%s'>", 
							$attributes['id'], 
							'Modules_Category_Services_Category::categoryCheckbox',
							$json->encodeUnsafe($attributes)) . self::EOL;
		
		foreach ($categories as $category) {
			$selected = (isset($attributes['selected']) && in_array($category['category_id'], $attributes['selected'])) 
						? ' checked="checked"' 
						: '';
						
			$output  .= '<div>' 
						. str_repeat('-----', $category['depth'])
						. ' <input type="checkbox" name="' . $attributes['name'] .'" value="' . $category['category_id'] . '"' . $selected. ' />' 
						. $category['name']
						. '</div>'
						. self::EOL;
		}
		$output .= '</div>' . self::EOL;
		
		return $output;
	}
	
	public static function getTree($lang = null, $module)
	{
		$lang = (null == $lang) ? Gio_Core_Config_Xml::getConfig('web')->language : $lang;
		$conn = Gio_Db_Connection::getConnection();
		$dao = new Modules_Category_Models_Mysql_Category();
		$dao->setLang($lang);
		$dao->setConnection($conn);
		return $dao->getTree($module);
	}
	
	public static function updateOrder($data) {
		$conn = Gio_Db_Connection::getConnection();
		$dao = new Modules_Category_Models_Mysql_Category();
		$dao->setConnection($conn);
		return $dao->updateOrder($data);
	}
	
	public static function getSubCategories($categoryId)
	{
		$conn = Gio_Db_Connection::getConnection();
		$dao = new Modules_Category_Models_Mysql_Category();
		$dao->setConnection($conn);
		return $dao->getSubCategories($categoryId);
	}
	
	/**
	 * Display select box listing all categories
	 * which haven't been translated from the default language
	 * 
	 * @param $attributes array
	 * @param string $lang
	 * @return string
	 */
	public static function translatableCategory($attributes = array(), $lang = null, $module, $disabled = false)
	{
		$json = new Services_JSON();
		$defaultLang     = (string)Gio_Core_Config_Xml::getConfig('web')->language;
		$lang = (null == $lang) ? $defaultLang : $lang;
		$elementDisabled = (null == $lang || $lang == $defaultLang) ? ' disabled="disabled"' : '';
		$elementDisabled = ($disabled) ? ' disabled="disabled"' : $elementDisabled;	
		
		$attributes['selected'] = isset($attributes['selected']) ? $attributes['selected'] : null;
		$attributes['disabled']  = isset($attributes['disabled']) ? $attributes['disabled'] : null;
		
		$categories 	 = self::getTranslatable($lang, $module);
		$output 		 = sprintf("<select name='%s' id='%s' viewHelperClass='%s' viewHelperAttributes='%s'%s>", 
								$attributes['name'], 
								$attributes['id'],
								'Modules_Category_Services_Category::translatableCategory',
								$json->encodeUnsafe($attributes), 
								$elementDisabled) . self::EOL
						. '<option value=\'{"id": "", "language": ""}\'>---</option>' . self::EOL;
		
		foreach ($categories as $category) {
			$disabled = (0 == (int)$category['translatable'] 
							&& ((0 == (int)$attributes['disabled'] && $category['category_id'] != (int)$attributes['selected'])
								||
							((int)$attributes['disabled'] == (int)$attributes['selected'])))
						? ' disabled="disabled"' 
						: '';
			$selected = ($elementDisabled == ''
							&& $disabled == ''
							&& (int)$category['category_id'] == (int)$attributes['selected'])
						? ' selected="selected"' 
						: '';
			
			$output  .= sprintf("<option value='%s'%s%s>%s</option>", 
								$json->encodeUnsafe(array('id' => $category['category_id'], 'language' => $defaultLang)), 
								$selected,
								$disabled,
								str_repeat('---', $category['depth']) . $category['name']) . self::EOL;
		}
		$output .= '</select>' . self::EOL;

		return $output;
	}
	
	public static function getTranslatable($lang, $module)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_Category_Models_Mysql_Category();
		$dao->setConnection($conn);
		return $dao->getTranslatable($lang, $module);
	}
	
	public static function getSource($category)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_Category_Models_Mysql_Category();
		$dao->setConnection($conn);
		return $dao->getSource($category);
	}
}